/***************************************************************************
 *   Copyright (C) 2007 by Pablo Marcondes Fonseca   *
 *   pablo@oneos.com.br   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 *                                                                         *
 *   In addition, as a special exception, the copyright holders give       *
 *   permission to link the code of this program with any edition of       *
 *   the Qt library by Trolltech AS, Norway (or with modified versions     *
 *   of Qt that use the same license as Qt), and distribute linked         *
 *   combinations including the two.  You must obey the GNU General        *
 *   Public License in all respects for all of the code used other than    *
 *   Qt.  If you modify this file, you may extend this exception to        *
 *   your version of the file, but you are not obligated to do so.  If     *
 *   you do not wish to do so, delete this exception statement from        *
 *   your version.                                                         *
 ***************************************************************************/


#include <QtGui>
#include "kickinstall.h"

KickInstall::KickInstall() {
    ui.setupUi ( this );
    ui.lbNumeroMaq->setVisible ( false );
    ui.leNumeroMaq->setVisible ( false );
    ui.lbTempo->setVisible ( false );
    ui.leTempo->setVisible ( false );

    connect ( ui.pbIniciar, SIGNAL ( clicked() ), this, SLOT ( pbIniciarClicked() ) );
    connect ( ui.tbArquivoImagem, SIGNAL ( clicked() ), this, SLOT ( tbArquivoImagemClicked() ) );
    connect ( ui.cbArquivoImagem, SIGNAL ( currentIndexChanged ( int ) ), this, SLOT ( cbArquivoImagemChanged()) );
    connect ( ui.pbDesligar, SIGNAL ( clicked() ), this, SLOT (pbDesligarClicked() ) );

    QDir dir ( "/home/partimag" );
    dir.setFilter ( QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot );
    dir.setSorting ( QDir::Time );

    QStringList listaImagens = dir.entryList();
    for ( int i = 0; i < listaImagens.size(); ++i ) {
        ui.cbArquivoImagem->addItem ( listaImagens.at ( i ) );
    }

    cbArquivoImagemChanged();

}

void KickInstall::pbIniciarClicked () {
    QString drblOcs = "/opt/drbl/sbin/drbl-ocs";
    QString acaoTerminar = "poweroff";
    QString nomeImagem = "imagem-" + QDate::currentDate().toString ( "dd_MM_yy" ) + "-img";
    QString nomeDisco = "hda";
    QString numeroMaquinas = "40";
    QString tempoEspera = "300";
    QString comandoExecutar = "";

    if ( ui.rbCriar->isChecked() ) { // criar imagem
        if ( ui.cbDisco->currentIndex() != 0 )
            nomeDisco = "sda";
        if ( ui.rbReiniciar->isChecked() )
            acaoTerminar = "reboot";
        if ( ui.cbArquivoImagem->count() > 0 )
            nomeImagem = ui.cbArquivoImagem->currentText();
        comandoExecutar = drblOcs + " -b -p " + acaoTerminar + " -z3 -l en startdisk save " + nomeImagem + " " + nomeDisco;
    } else { // clonar máquinas
        if ( ui.cbDisco->currentIndex() != 0 )
            nomeDisco = "sda";
        if ( ui.rbReiniciar->isChecked() )
            acaoTerminar = "reboot";
        if ( ui.cbArquivoImagem->count() > 0 )
            nomeImagem = ui.cbArquivoImagem->currentText();
        numeroMaquinas = ui.leNumeroMaq->text();
        tempoEspera = QString ( "%1" ).arg ( ui.leTempo->text().toInt() * 60 );
        comandoExecutar = drblOcs + " -b -g auto -x -p " + acaoTerminar + " --clients-to-wait " + numeroMaquinas + " --max-time-to-wait " + tempoEspera + " -l en startdisk multicast_restore " + nomeImagem + " " + nomeDisco;
    }

    QFile::remove ( "/var/log/clonezilla-jobs.log" );
    qDebug() << comandoExecutar.toLatin1();
    QProcess process;
    process.execute ( comandoExecutar );

    QTimer *timer = new QTimer ( this );
    connect ( timer, SIGNAL ( timeout() ), this, SLOT ( atualizaProgresso() ) );
    timer->start ( 1000 );

    progresso =  new QProgressDialog ( this );
    progresso->setWindowModality ( Qt::WindowModal );
    progresso->setLabelText ( "Executando tarefas solicitadas..." );
    progresso->setMinimum ( 0 );
    progresso->setMaximum ( 100 );
    progresso->setValue ( 1 );
}

void KickInstall::tbArquivoImagemClicked() {
// coloca mouse no centro da tela
QCursor mouse = QCursor();
mouse.setPos(this->geometry().width()/2, this->geometry().height()/2);
qDebug() << this->geometry().width() << " " << this->geometry().height();
    bool ok;
    QString nomeImagem = QInputDialog::getText ( this, tr ( "One OS KickInstall - Arquivo de Imagem" ),
                         tr ( "Digite o nome do arquivo de imagem:" ), QLineEdit::Normal,
                         "imagem-" + QDate::currentDate().toString ( "dd_MM_yy" ) + "-img", &ok );
    if ( ok && !nomeImagem.isEmpty() ) {
        if ( ui.cbArquivoImagem->findText ( nomeImagem ) == -1 ) // se nao existe no combobox
            ui.cbArquivoImagem->addItem ( nomeImagem );
    }
    ui.cbArquivoImagem->setCurrentIndex( ui.cbArquivoImagem->count() -1);
}

void KickInstall::atualizaProgresso() {
    QFile logfile ( "/var/log/clonezilla-jobs.log" );
    if ( !logfile.open ( QIODevice::ReadOnly | QIODevice::Text ) )
        return;

    QString strTermino = "finished cloning";

    while ( !logfile.atEnd() ) {
        QByteArray line = logfile.readLine();
        if ( QString ( line ).indexOf ( strTermino, 10 ) != -1 ) {
            progresso->setValue ( 100 );
            QProcess process;
            process.execute ( "/opt/drbl/sbin/drbl-ocs stop");
        }
    }
    logfile.close();
}

void KickInstall::pbDesligarClicked() {
    QProcess process;
    process.execute ( "shutdown -h now" );
}

void KickInstall::cbArquivoImagemChanged() {
    QFile arquivoDisco ( "/home/partimag/" + ui.cbArquivoImagem->currentText() + "/disk" );
    if ( !arquivoDisco.open ( QIODevice::ReadOnly | QIODevice::Text ) ) {
        qDebug() << tr("Arquivo de disco não pode ser aberto.").toLatin1();
        return;
    }

    QByteArray line = arquivoDisco.readLine();
    if ( QString ( line ).startsWith ( "sda" ) ) {
        ui.cbDisco->setCurrentIndex ( 1 );
    }
    arquivoDisco.close();
}
